import io
import json
import os
from flask import Flask, request, jsonify, Response, render_template
import base64
import cv2
from io import BytesIO
from PIL import Image
import numpy as np
import dlib
import face_recognition
from flask_cors import CORS
from datetime import datetime
from sqlalchemy import create_engine, Table, Column, Integer, DateTime, String, Enum, MetaData, LargeBinary, insert
from sqlalchemy.orm import scoped_session, sessionmaker
import uuid
app = Flask(__name__, static_folder='static', template_folder='templates')
CORS(app)
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost:3306/flask_sql'

# 创建 MySQL 数据库连接
engine = create_engine('mysql+pymysql://root:root@localhost:3306/flask_sql', echo=True)
# 定义数据表
metadata = MetaData()

# 创建数据表
metadata.create_all(engine)

Session = scoped_session(sessionmaker(bind=engine))
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor('./dat/shape_predictor_68_face_landmarks.dat')
facerec =dlib.face_recognition_model_v1('./dat/dlib_face_recognition_resnet_model_v1.dat')
registered_faces_file = 'registered_faces.json'

# 创建截图保存目录
#save_directory = "screenshots"
#os.makedirs(save_directory, exist_ok=True)

def load_registered_faces():
    if os.path.exists(registered_faces_file):
        with open(registered_faces_file, 'r') as file:
            return json.load(file)
    return {}

registered_faces = load_registered_faces()

@app.route('/face-register', methods=['POST'])
def face_register():
    data = request.get_json()
    staff_name = data['staff_id']
    image_data = data['image']

    # 解码并转换为 PIL 图像，然后转为 NumPy 数组以便 dlib 处理
    image = Image.open(BytesIO(base64.b64decode(image_data)))
    image_np = np.array(image)

    # 使用 detector 检测图像中的人脸，然后通过 sp 获取关键点，facerec 生成人脸编码。
    faces = detector(image_np, 1)
    if len(faces) != 1:
        return jsonify({'error': 'No face or multiple faces detected'}), 400

    shape = sp(image_np, faces[0])
    face_descriptor = facerec.compute_face_descriptor(image_np, shape)
    face_descriptor_list = [x for x in face_descriptor]

    # 人脸编码存储在 JSON 文件中，与工作人员 ID 关联
    registered_faces[staff_name] = face_descriptor_list
    with open(registered_faces_file, 'w') as file:
        json.dump(registered_faces, file)

    return jsonify({'message': 'Face registered successfully'})

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)